import './Css/Tab.css';
import React from 'react';
import CodeMirror from '@uiw/react-codemirror';
import { MySQL, sql } from '@codemirror/lang-sql';
import { w2utils, w2grid } from "w2ui/w2ui-2.0.es6"
import { githubLight } from '@uiw/codemirror-theme-github';
import { Delete, Records } from '../wailsjs/go/main/App';
import { IconCollapse, IconTable } from '@douyinfe/semi-icons-lab';
import { Tabs, TabPane, Spin, Pagination, Button } from '@douyinfe/semi-ui';

const grids = new Map();

class Tab extends React.Component {
    constructor(props) {
        super(props);
        this.gridName = this.props.table + '_grid';
        const database = this.props.database;
        const table = this.props.table;
        const fields = this.props.fields;

        this.config = {
            grid: {
                name: this.gridName,
                selectType: 'cell',
                recordHeight: 30,
                show: {
                    toolbar: true,
                    footer: true,
                    lineNumbers: true,
                    toolbarColumns: false,
                    toolbarSearch: true,
                    toolbarAdd: true,
                    toolbarDelete: false,
                    toolbarSave: true
                },
                searches: [],
                contextMenu: [
                    { id: 'view', text: 'View', icon: 'w2ui-icon-info' },
                    { id: 'edit', text: 'Edit', icon: 'w2ui-icon-pencil' },
                    { text: '--' },
                    { id: 'delete', text: 'Delete', icon: 'w2ui-icon-cross' },
                ],
                onContextMenuClick(event) {
                    console.log(event.detail)
                    switch (event.detail.menuItem.id) {
                        case "delete":
                            return this.deleteRecord(event.detail) // 删除数据记录
                    }
                },
                deleteRecord({ recid, column }) {
                    if (column > -1) return;
                    const record = this.get(recid);
                    if (!record) {
                        w2utils.notify('无法定位数据', { error: true });
                        return;
                    }
                    const query = this.buildWhere(record);
                    console.log(query);
                    Delete(database, table, query[0], query[1], 1).then((result) => {
                        if (result) this.remove(recid);
                        else w2utils.notify('删除数据失败, 缺少关键参数', { error: true })
                    });
                },

                buildWhere(record) {
                    let conditions = '';
                    let bind = [];
                    const _temp = fields.filter(field => field.Key == 'PRI');

                    if (_temp.length > 0) {
                        let field = _temp[0]
                        conditions = field.Field + " = ?"
                        bind.push(record[field.Field])
                    } else {
                        conditions = []
                        for (let i in fields) {
                            let field = fields[i]
                            conditions.push(field.Field + " = ?")
                            bind.push(record[field.Field])
                        }
                        conditions = conditions.join(' AND ')
                    }
                    return [conditions, bind];
                },

                onColumnClick(event) {
                    this.selectNone(true)
                    let sel = []
                    let column = this.getColumn(event.detail.field, true)
                    for (let i = 0; i < this.total; i++) {
                        sel.push({ recid: this.records[i].recid, column: column })
                    }
                    this.select(sel)
                    event.preventDefault()
                },
                onDelete(event) {
                    event.detail.force = true
                },
                async onSelect(event) {
                    await event.complete
                    console.log('select', event.detail, this.getSelection())
                },
                async onClick(event) {
                    await event.complete
                    console.log('click', event.detail)
                }
            }
        }


        this.state = {
            loading: true,
            locker: {},
            sql: {
                tables: [{
                    label: 'crm_jobs',
                    displayLabel: 'crm_jobs'
                }],
                upperCaseKeywords: true,
                dialect: MySQL
            },
            pagination: {
                page: 1,
                pageSize: 100,
                total: 0
            },
            tabList: [

            ],
            value: "",
            fields: props.fields
        };

        this.sheet(1);
    }

    componentDidMount() {
        // 设置表格显示
        this.setState({
            tabList: [
                {
                    tab: <span> <IconTable /> crm_jobs </span>, itemKey: '1', content: <>
                        <div id="main" style={{ height: 928 }}></div>
                        <div style={{ textAlign: 'center' }}>
                            <div style={{ float: 'left' }}>
                                <Button theme='borderless' type='primary' style={{ marginRight: 8 }}>结构</Button>
                                <Button theme='borderless' type='primary' style={{ marginRight: 8 }}>数据</Button>
                                <Button theme='borderless' type='secondary' style={{ marginRight: 8 }}>总数</Button>
                            </div>
                            <Pagination pageSize={this.state.pagination.pageSize} total={2000} size="small"
                                onChange={(currentPage, pageSize) => {
                                    this.sheet(currentPage)
                                }} style={{ float: 'right' }}></Pagination>
                        </div>
                    </>, closable: true
                },
                {
                    tab: <span> <IconCollapse /> Query</span>, itemKey: '3', content: <CodeMirror value={'SELECT 1'} theme={githubLight} height="960px" extensions={[sql(this.state.sql)]} />
                }
            ]
        });
    }




    close(key) {
        const newTabList = [...this.state.tabList];
        const closeIndex = newTabList.findIndex(t => t.itemKey === key);
        newTabList.splice(closeIndex, 1);
        this.setState({ tabList: newTabList });
    }

    render() {
        return (
            <Spin spinning={this.state.loading} tip="loading...">
                <div>
                    <Tabs type='card' defaultActiveKey="1" tabPaneMotion={false} onTabClose={this.close.bind(this)}>
                        {
                            this.state.tabList.map(t => <TabPane size={'size'} type={'button'} closable={t.closable} tab={t.tab} itemKey={t.itemKey} key={t.itemKey}>{t.content}</TabPane>)
                        }
                    </Tabs>
                </div>
            </Spin>
        );
    }

    sheet(page = 1) {
        /**
         * 单元格编辑器
         * @param {string} field 
         * @returns
         */
        const getEditor = (field) => {
            switch (field) {
                case "date":
                case "datetime":
                    return field
                case "timestamp":
                    return "datetime"
                case "int", "tinyint":
                    return "int";
                default:
                    if (field?.includes("float") || field?.includes("decimal")) {
                        return "float"
                    }
                    return "text"
            }
        };

        /**
         * 获取组件渲染
         * @param {string} field 
         * @param {Object} value 
         * @returns 
         */
        const getRender = (type, field) => {
            return function (rec, extra) {
                if (typeof rec[field] === 'undefined' || rec[field] === null) {
                    return "<div style='color:#d9d9d9'>(NULL)</div>"
                } else if (!rec[field]) {
                    return "<div style='color:#d9d9d9'>(EMPTY)</div>"
                }
                switch (type) {
                    case "date":
                        return "yyyy-mm-dd"
                    case "datetime":
                    case "timestamp":
                        return "yyyy-mm-dd HH:mi:ss"
                }
                return rec[field]
            };
        };


        if (this.props.fields && this.props.table) {
            this.state.loading = true
            Records(this.props.database, this.props.table, page * 100).then((items) => {
                const columns = []
                const searches = []
                const fieldType = {};
                this.props.fields?.map((item, index) => {
                    fieldType[item.Field] = item.Type;
                    columns.push({
                        text: '<div style="text-align: center; font-size: 12px; color: #000; font-weight: 500">' + (item.Key == 'PRI' ? '🔑' : '') + item.Field + '<font style="margin-left: 5px; font-size:8px; color:gray">' + item.Type + '</font></div>',
                        editable: item.readonly ? false : (item.Key != 'PRI' ? { type: getEditor(item.Type) } : false),
                        size: (item.Field?.length + parseInt(item.Type?.length * 0.8) + 7) * 6 + 'px',
                        render: getRender(item.Type, item.Field),
                        field: item.Field,
                        resizable: true,
                        sortable: true,
                    })
                    searches.push({ field: item.Field, label: item.Field, type: 'text' });
                })

                if (!grids.has(this.gridName) && this.props.table) {
                    const _config = { ...this.config.grid }
                    _config.searches = searches
                    grids.set(this.gridName, new w2grid(_config));
                };

                const grid = grids.get(this.gridName)
                grid.columns = columns
                grid.records = []

                items?.map((item, index) => {
                    for (let i in item) {
                        if (item[i] && getEditor(fieldType[i]).includes('date')) {
                            item[i] = item[i].replace('T', ' ').split('+')[0]
                        }
                    }
                    grid.records.push(w2utils.extend({ recid: index + 1 }, item));
                })

                if (page == 1) {
                    // Total(this.props.database, this.props.table).then((total) => {
                    //     Toast.success(total + "条数据")
                    //     let pagination = this.state.pagination;
                    //     pagination.total = total
                    //     grid.total = total
                    //     grid.buffered = total
                    //     // this.setState({ pagination })
                    // })
                    grid.render('#main') // ?Locker
                }
                grid.reload();
                this.setState({ loading: false })
            })
        }
    }
}

export default Tab;

